package com.atzly.community.datasource;

import com.atzly.community.datasource.util.ContextHelper;
import com.google.common.cache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataSourceConfigCache {
  private static final Logger logger = LoggerFactory.getLogger(DataSourceConfigCache.class);

  private static final int CONCURRENCY_LEVEL = 8;
  private static final int INITIAL_CAPACITY = 1000;
  private static final long MAX_CACHE_SIZE = 50000L;
  private static final String DB_ID_CACHE_FORMAT = "%1$s_%2$s";

  private static final Cache<String, String> DB_MAP_CACHE = CacheBuilder.newBuilder().concurrencyLevel(CONCURRENCY_LEVEL)
      .initialCapacity(INITIAL_CAPACITY).maximumSize(MAX_CACHE_SIZE).recordStats().removalListener(new RemovalListener<String, String>() {
        @Override
        public void onRemoval(RemovalNotification<String, String> notification) {
          logger.info("db map cache was removed, orgId:{}, cause:{}", notification.getKey(), notification.getCause());
        }
      }).build();

  @Deprecated // TODO
  public static String getDbId(Long orgId) {
    return getDbId(ContextHelper.getServiceContext().getMainAppId(), orgId);
  }

  @Deprecated // TODO
  public static void setDbId(Long orgId, String dbId) {
    setDbId(ContextHelper.getServiceContext().getMainAppId(), orgId, dbId);
  }

  public static String getDbId(Long appId, Long orgId) {
    String cacheKey = getCacheKey(appId, orgId);
    String dbId = DB_MAP_CACHE.getIfPresent(cacheKey);
    return dbId;
  }

  public static void setDbId(Long appId, Long tenantId, String dbId) {
    String cacheKey = getCacheKey(appId, tenantId);
    DB_MAP_CACHE.put(cacheKey, dbId);
  }

  private static String getCacheKey(Long appId, Long orgId) {
    return String.format(DB_ID_CACHE_FORMAT, appId, orgId);
  }
}
